import React, { useEffect, useState } from 'react'
import styles from './QuestionCheckbox.module.scss'

interface PropsType {
  fe_id: string
  props: {
    title: string
    isVertical: boolean
    list: Array<{
      value: string
      text: string
      checked: boolean
    }>
  }
}

const QuestionCheckbox: React.FC<PropsType> = ({ fe_id, props }) => {
  const { title, isVertical, list = [] } = props
  const [selectedValues, setSelectedValues] = useState<string[]>([])

  // 初始化时,判断默认选中
  useEffect(() => {
    list.forEach(item => {
      const { value, checked } = item
      if (checked) {
        setSelectedValues(selectedValues => [...selectedValues, value])
      }
    })
  }, [list])

  function toggleChecked(value: string) {
    if (selectedValues.includes(value)) {
      // 已经选中了,则取消选择
      setSelectedValues(selectedValues.filter(v => v !== value))
    } else {
      setSelectedValues([...selectedValues, value])
    }
  }

  return (
    <>
      <p>{title}</p>
      <input type="hidden" name={fe_id} value={selectedValues.toString()} />
      <ul className={styles.list}>
        {list.map(({ value, text }) => {
          return (
            <li
              key={value}
              className={isVertical ? styles['vertical-item'] : styles['horizontal-item']}
            >
              <label>
                <input
                  type="checkbox"
                  checked={selectedValues.includes(value)}
                  onChange={() => {
                    toggleChecked(value)
                  }}
                />
                {text}
              </label>
            </li>
          )
        })}
      </ul>
    </>
  )
}

export default QuestionCheckbox
